package com.googlecode.yoohoo.host;

import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.osgi.framework.BundleContext;

import com.googlecode.yoohoo.config.DefaultConfigManager;
import com.googlecode.yoohoo.config.IConfigManager;
import com.googlecode.yoohoo.config.OptionDescription;
import com.googlecode.yoohoo.osgi.AbstractBundleActivator;
import com.googlecode.yoohoo.utils.Constants;

public class Activator extends AbstractBundleActivator {
	private static final Log log = LogFactory.getLog(Activator.class);
	
	private static final String KEY_ECLIPSE_HOME_LOCATION = "eclipse.home.location";
	
	private Host host;
	
	/*
	 * (non-Javadoc)
	 * @see org.osgi.framework.BundleActivator#start(org.osgi.framework.BundleContext)
	 */
	public void doStart(BundleContext context) throws Exception {
		host = new Host();		
		try {
			host.start(context);
		} catch (Exception e) {
			e.printStackTrace();
			throw e;
		}
		
		log.info("YooHoo host started");
	}

	/*
	 * (non-Javadoc)
	 * @see org.osgi.framework.BundleActivator#stop(org.osgi.framework.BundleContext)
	 */
	public void doStop(BundleContext context) throws Exception {
		try {
			host.stop(context);
		} catch (Exception e) {
			e.printStackTrace();
			throw e;
		}
		
		log.info("YooHoo host stopped.");
	}
	
	@Override
	protected IConfigManager getConfigManager(BundleContext context)
			throws Exception {
		String appHome = getAppHome();
		
		String configHome = appHome + "/configuration";
		IConfigManager configManager = new HostConfigManager(configHome);
		
		configManager.setString(Constants.KEY_APP_HOME, appHome);
		configManager.setString(Constants.KEY_CONFIG_HOME, configHome);

		return configManager;
	}
	
	private String getAppHome() {
		String appHome = null;
		try {
			appHome = new URL(System.getProperty(KEY_ECLIPSE_HOME_LOCATION)).getFile();
		} catch (MalformedURLException e) {
			throw new RuntimeException(e);
		}
		if (appHome == null || "".equals(appHome))
			throw new RuntimeException("Can't determine application home.");
		
		if (appHome.endsWith("/")) {
			appHome = appHome.substring(0, appHome.length() - 1);
		}
		
		return appHome;
	}
	
	private class HostConfigManager extends DefaultConfigManager {
		private String configHome;
		
		public HostConfigManager(String configHome) {
			this.configHome = configHome;
		}
		
		@Override
		public String getConfigPath() {
			return configHome + "/host.config";
		}
		
		@Override
		protected List<OptionDescription> getOptionDescriptions() {
			List<OptionDescription> optionDescriptions = new ArrayList<OptionDescription>();
			optionDescriptions.add(new OptionDescription(Constants.KEY_HOST_NAME, String.class, "127.0.0.1"));
			
			return optionDescriptions;
		}
	}

}
